import { DataSource } from "typeorm";

import { production_schema_list, toNumber } from "qqlx-cdk";

export class PgClient {
  logger: boolean = false;
  serverHost: string;
  serverPort: string;
  serverDatabaseName: string;
  serverUserName: string;
  serverPassword: string;

  serverClient!: DataSource;

  constructor(host: string, port: string, dbName: string, username: string, pwd: string, logger?: boolean) {
    this.serverHost = host;
    this.serverPort = port;
    this.serverDatabaseName = dbName;
    this.serverUserName = username;
    this.serverPassword = pwd;

    this.logger = !!logger;
  }

  async start() {
    this.serverClient = new DataSource({
      type: "postgres",
      host: this.serverHost,
      port: toNumber(this.serverPort),
      username: this.serverUserName,
      password: this.serverPassword,
      database: this.serverDatabaseName,
      logging: false,
      entities: production_schema_list,
    });
    await this.serverClient.initialize();
    this.logger && console.log("🏀 Postgresql > 初始化实例成功", this.serverDatabaseName);

    return this.serverClient;
  }

  async stop() {
    this.serverClient && (await this.serverClient.destroy());
    this.logger && console.log("🏀 Postgresql > 数据库控制器：已经关闭数据库实例");
  }
}
